//
//  MORegistSureViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/7/29.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MORegistSureViewController.h"
#import "MOForgotPasswordViewCell.h"

@interface MORegistSureViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
//数据数组
@property(nonatomic,strong)NSMutableArray *dataArray;
//footer
@property(nonatomic,strong)UIView *footerView;
//确认按钮
@property(nonatomic,strong)UIButton *sureSetButton;
//取消按钮
@property(nonatomic,strong)UIButton *cancelSetButton;
//性别
@property(nonatomic,strong)NSMutableArray *sexButtonArray;
//局
@property(nonatomic,strong)NSMutableArray *juButtonArray;
//
@property(nonatomic,assign)NSInteger firstSelectedIndex;
//
@property(nonatomic,assign)NSInteger secondSelectedIndex;
//
@property(nonatomic,strong)NSMutableArray *allOrganizationArray;
//
@property(nonatomic,strong)NSMutableArray *firstArray;
//
@property(nonatomic,strong)NSMutableArray *secondArray;

@end

@implementation MORegistSureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    
    [self creatView];
    
    [self initData];

}

-(void)creatView
{
    [self.view addSubview:self.tableView];
    
    self.tableView.tableFooterView = self.footerView;
}


-(void)initData
{
    self.dataArray = [NSMutableArray array];
    NSArray *nameArr = @[@"姓名",@"手机号",@"请输入用户名",@"请输入验证码",@"请输入密码",@"再次输入新密码"];
    NSArray *paleArr = @[@"请输入姓名",@"请输入手机号",@"请输入用户名",@"请输入验证码",@"请输入8-16位密码",@"请输入8-16位密码"];
    for (int i = 0; i<nameArr.count; i++) {
        MOForgotPasswordModel *model = [[MOForgotPasswordModel alloc]init];
        model.nameStr = nameArr[i];
        model.placeStr = paleArr[i];
        if (i==0) {
            model.valueStr = self.nameStr;
        }
        if (i==1) {
            model.valueStr = self.telStr;
        }
        if (i>2) {
            model.secureKeyword = @"1";
        }
        if (i==3) {
            model.type = @"1";
        }else{
            model.type = @"0";
        }
        [self.dataArray addObject:model];
    }
    [self.tableView reloadData];
    
    
    self.firstSelectedIndex = 0;
    self.secondSelectedIndex = 0;
    NSString *postUrl = [NSString stringWithFormat:@"%@?parentId=0",ORG_GETORGLISTBYPID_URL];
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"组织树:%@",responseObject);
        if (![responseObject isKindOfClass:[NSArray class]]) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"组织树数据错误" showInView:self.view];
            return ;
        }
        self.allOrganizationArray = [NSMutableArray arrayWithArray:responseObject];
        self.firstArray = [NSMutableArray array];
        self.secondArray = [NSMutableArray array];
        for (int i = 0; i<self.allOrganizationArray.count; i++) {
            [self.firstArray addObject:self.allOrganizationArray[i][@"text"]];
            if (i==0) {
                NSArray *arr = self.allOrganizationArray[i][@"children"];
                for (int j = 0; j<arr.count; j++) {
                    [self.secondArray addObject:arr[j][@"text"]];
                }
            }
        }
        UIButton *button1 = self.juButtonArray[0];
        UIButton *button2 = self.juButtonArray[1];
        [button1 setTitle:self.firstArray[0] forState:UIControlStateNormal];
        [button2 setTitle:self.secondArray[0] forState:UIControlStateNormal];
        
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -- 获取验证码
- (void)getTelCode
{
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@",A_CAPTCHA_URL,@"REGISTER",self.telStr];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"获取验证码:%@",responseObject);
        if ([responseObject integerValue]==0) {
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送成功" showInView:self.view];
        }else if ([responseObject integerValue]==1){
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送异常" showInView:self.view];
        }else if ([responseObject integerValue]==2){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户不存在" showInView:self.view];
        }else if ([responseObject integerValue]==3){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户为注册手机号码" showInView:self.view];
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:@"短信接口调用异常" showInView:self.view];
        }
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MOForgotPasswordViewCell *setCell = [MOForgotPasswordViewCell cellWithTableView:tableView andIndexPath:indexPath];
    MOForgotPasswordModel *model = self.dataArray[indexPath.row];
    setCell.model = model;
    if (indexPath.row==0) {
        setCell.textField.userInteractionEnabled = NO;
    }else if (indexPath.row==1){
        setCell.textField.userInteractionEnabled = NO;
    }else{
        setCell.textField.userInteractionEnabled = YES;
    }

    __weak typeof (self)weakSelf = self;
    setCell.clickCodeButtonBlock = ^{
        [weakSelf getTelCode];
    };
    setCell.endEditingBlock = ^(NSString * _Nonnull text) {
        model.valueStr = text;
    };
    return setCell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHConversions(12)*4+12+15+13;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        
    }
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 35, 0, 35)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 35, 0, 35)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 35, 0, 35)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 35, 0, 35)];
    }
}

#pragma mark -- 返回
-(void)clickBackBtn
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -- 确定
-(void)clickSureResetButton
{
    MOForgotPasswordViewCell *cell0 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    MOForgotPasswordViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    MOForgotPasswordViewCell *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    MOForgotPasswordViewCell *cell3 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    MOForgotPasswordViewCell *cell4 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    
    MOForgotPasswordViewCell *cell5 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
    
    
    if (cell2.textField.text.length==0) {
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==2) {
                model.showField = @"1";
                model.fieldNameStr = @"用户名不能为空";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    if (cell3.textField.text.length==0) {
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==3) {
                model.showField = @"1";
                model.fieldNameStr = @"验证码不能为空";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    if (cell4.textField.text.length<8||cell4.textField.text.length>16) {
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==4) {
                model.showField = @"1";
                model.fieldNameStr = @"请输入8-16位密码";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    if (cell5.textField.text.length<8||cell5.textField.text.length>16) {
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==5) {
                model.showField = @"1";
                model.fieldNameStr = @"请输入8-16位密码";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    if (![cell4.textField.text isEqualToString:cell5.textField.text]) {
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==5) {
                model.showField = @"1";
                model.fieldNameStr = @"两次密码不一致";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    for (int i = 0; i<self.dataArray.count; i++) {
        MOForgotPasswordModel *model = self.dataArray[i];
        model.showField = @"0";
        model.fieldNameStr = @"";
    }
    [self.tableView reloadData];
    
    
    NSDictionary *user = @{
                           @"userName":cell2.textField.text,
                           @"name":cell0.textField.text,
                           @"password":[self sha1:[NSString stringWithFormat:@"%@%@",cell4.textField.text,cell2.textField.text]],
                           @"phone":cell1.textField.text,
                           @"org_id":self.allOrganizationArray[self.firstSelectedIndex][@"children"][self.secondSelectedIndex][@"value"],
                           @"status":@"0",
                           @"captcha":cell3.textField.text
                           };
    NSString *postUrl = [NSString stringWithFormat:@"%@",USER_INSERTUSER_URL];
    
    [[ADShowMessage shareShowMessage] showHUDAddedTo:self.view animated:YES];
    
    [PPNetworkHelper POST:postUrl parameters:user success:^(id responseObject) {
        NSLog(@"注册:%@",responseObject);
        
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"registSucess" object:nil userInfo:@{@"userName":cell2.textField.text}];
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:responseObject[@"msg"] showInView:WINDOW];
        }
    } failure:^(NSError *error) {
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:WINDOW];
    }];
    
}

#pragma mark - sha1加密方式
- (NSString *) sha1:(NSString *)input
{
    //这两句容易造成 、中文字符串转data时会造成数据丢失
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    //instead of
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

#pragma mark -- 选择局
-(void)clickSelectedButton:(UIButton *)sender
{
    if (sender.tag==0) {
        SNXYSelectedNumberView *pickview = [[SNXYSelectedNumberView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        pickview.numberArray = [NSArray arrayWithArray:self.firstArray];
        __weak typeof (self)weakSelf = self;
        pickview.clickIndexBlock = ^(NSInteger index) {
            weakSelf.firstSelectedIndex = index;
            UIButton *button = self.juButtonArray[0];
            [button setTitle:self.firstArray[index] forState:UIControlStateNormal];
            
            NSArray *arr = self.allOrganizationArray[index][@"children"];
            weakSelf.secondArray = [NSMutableArray array];
            weakSelf.secondSelectedIndex = 0;
            for (int i = 0; i<arr.count; i++) {
                [weakSelf.secondArray addObject:arr[i][@"text"]];
            }
            UIButton *button1 = self.juButtonArray[1];
            [button1 setTitle:self.secondArray[0] forState:UIControlStateNormal];
        };
        [WINDOW addSubview:pickview];
    }else{
        SNXYSelectedNumberView *pickview = [[SNXYSelectedNumberView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        pickview.numberArray = [NSArray arrayWithArray:self.secondArray];
        __weak typeof (self)weakSelf = self;
        pickview.clickIndexBlock = ^(NSInteger index) {
            weakSelf.secondSelectedIndex = index;
            UIButton *button = self.juButtonArray[1];
            [button setTitle:self.secondArray[index] forState:UIControlStateNormal];
        };
        [WINDOW addSubview:pickview];
    }
}

#pragma mark -- 懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight-TabbarSafeBottomMargin) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
        
//        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(35, 10, 30, 25)];
//        label.text = @"性别";
//        label.textColor = KBlackColor_222222;
//        label.font = FONT_SIZE(12);
//        [_footerView addSubview:label];
        
//        self.sexButtonArray = [NSMutableArray array];
//        NSArray *title = @[@" 男",@" 女"];
//        for (int i = 0; i<title.count; i++) {
//            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(label.right + 10 + kWConversions(120) * i, 0, kWConversions(120), 25)];
//            button.centerY = label.centerY;
//            [button setTitle:title[i] forState:UIControlStateNormal];
//            [button setTitleColor:KBlackColor_222222 forState:UIControlStateNormal];
//            button.titleLabel.font = [UIFont boldSystemFontOfSize:12];
//            [button setImage:IMAGE(@"sexNormal") forState:UIControlStateNormal];
//            [button setImage:IMAGE(@"sexSelected") forState:UIControlStateSelected];
//            if (i==0) {
//                button.selected = YES;
//            }
//            [_footerView addSubview:button];
//            [self.sexButtonArray addObject:button];
//        }
        
        self.juButtonArray = [NSMutableArray array];
        CGFloat buttonW = SCREEN_WIDTH - 70;
        for (int i = 0; i<2; i++) {
            UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(35, 10 + (37 + 20)*i, buttonW, 37)];
            backView.layer.masksToBounds = YES;
            backView.layer.cornerRadius = 3.0;
            backView.layer.borderWidth = 1;
            backView.layer.borderColor = KGrayColor_d7d7d7.CGColor;
            [_footerView addSubview:backView];
            
            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(13, 0, backView.width - 13, backView.height)];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 3.0;
            [button setTitleColor:KBlackColor_222222 forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont boldSystemFontOfSize:12];
            button.tag = i;
            [button setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
            [button addTarget:self action:@selector(clickSelectedButton:) forControlEvents:UIControlEventTouchUpInside];
            [backView addSubview:button];
            [self.juButtonArray addObject:button];
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(backView.width - 21, 0, 12, 8)];
            imageView.centerY = backView.height/2;
            imageView.userInteractionEnabled = YES;
            imageView.image = IMAGE(@"down_blue");
            [backView addSubview:imageView];
        }
        
        _sureSetButton = [[UIButton alloc]initWithFrame:CGRectMake(35,50 + 37*2, SCREEN_WIDTH-70, 45)];
        [_sureSetButton setTitle:@"注册" forState:UIControlStateNormal];
        [_sureSetButton addTarget:self action:@selector(clickSureResetButton) forControlEvents:UIControlEventTouchUpInside];
        [_sureSetButton setBackgroundColor:KBlueColor_2C94FF];
        _sureSetButton.titleLabel.font = FONT_SIZE(15);
        _sureSetButton.layer.masksToBounds = YES;
        _sureSetButton.layer.cornerRadius = 3.0;
        [_footerView addSubview:_sureSetButton];
        
        _cancelSetButton = [[UIButton alloc]initWithFrame:CGRectMake(35, _sureSetButton.bottom + 20, SCREEN_WIDTH-70, 45)];
        [_cancelSetButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelSetButton addTarget:self action:@selector(clickBackBtn) forControlEvents:UIControlEventTouchUpInside];
        [_cancelSetButton setTitleColor:KBlackColor_222222 forState:UIControlStateNormal];
        _cancelSetButton.titleLabel.font = FONT_SIZE(15);
        _cancelSetButton.layer.masksToBounds = YES;
        _cancelSetButton.layer.cornerRadius = 3.0;
        _cancelSetButton.layer.borderWidth = 1;
        _cancelSetButton.layer.borderColor = KGrayColor_d7d7d7.CGColor;
        [_footerView addSubview:_cancelSetButton];
        
        _footerView.height = _cancelSetButton.bottom + 50;
    }
    return _footerView;
}

@end
